﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace XFFSM
{
    public class GraphLayer
    {

        #region 字段

        protected Rect position;

        private Matrix4x4 transormMatrix = Matrix4x4.identity;

        #endregion

        #region 属性

        public FSMEditorWindow EditorWindow { get; private set; }

        protected Context Context => EditorWindow.Context;

        #endregion


        #region 方法

        public GraphLayer(FSMEditorWindow editorWindow) {
            this.EditorWindow = editorWindow;
        }

        public virtual void OnGUI(Rect rect) {
            position = rect;
            UpdateTransformationMatrix();
        }

        public virtual void ProcessEvents() { 
            
        }

        public virtual void Update() { }

        private void UpdateTransformationMatrix() {
            var centerMat = Matrix4x4.Translate(-position.center);
            var translationMat = Matrix4x4.Translate(this.Context.DragOffset / this.Context.ZoomFactor);
            var scaleMat = Matrix4x4.Scale(Vector3.one * this.Context.ZoomFactor);

            this.transormMatrix = centerMat.inverse * scaleMat * translationMat * centerMat;
        }

        public Rect GetTransformedRect(Rect rect) {
            Rect result = new Rect();
            result.position = transormMatrix.MultiplyPoint(rect.position);
            result.size = transormMatrix.MultiplyVector(rect.size);

            return result;
        }

        public virtual void OnLostFocus()
        {
            if (UnityEditor.EditorWindow.mouseOverWindow != null && UnityEditor.EditorWindow.mouseOverWindow.GetType().ToString().Equals("UnityEditor.InspectorWindow"))
                return;
            this.Context.ClearSelections();
        }

        #endregion
    }

}

